from django.shortcuts import render
from .models import User


##列表
def index(request):
    context = {}
    context['items'] = User.objects.all()
    return render(request, 'index.html', context)


##添加
def add(request):
    if request.method == "POST":
        username = request.POST.get("username")
        nickname = request.POST.get("nickname")
        userDao = User()
        userDao.username = username
        userDao.nickname = nickname
        userDao.save()
        context = {
            'success': '添加成功',
        }
        return render(request, 'add.html', context)
    else:
        return render(request, 'add.html')


##详情
def detail(request):
    id = request.GET.get("id")
    userModel = User.objects.get(id=id)
    context = {}
    context['user'] = userModel
    return render(request, 'detail.html', context)


##删除
def delete(request):
    id = request.GET.get("id")
    User.objects.filter(id=id).delete()
    context = {
        'success': '删除成功',
    }
    return render(request, 'delete.html', context)


def update(request):
    if request.method == "POST":
        id = request.POST.get("id")
        username = request.POST.get("username")
        nickname = request.POST.get("nickname")
        userModel = User.objects.get(id=id)
        userModel.username = username
        userModel.nickname = nickname
        userModel.save()
        context = {}
        context['items'] = User.objects.all()
        return render(request, 'index.html', context)
